﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace mklib.json
{
	/// <summary>
	/// JsonValue解析器结果容器
	/// </summary>
	internal class JsonValue: IJsonValue
	{
		internal JsonValue (object value, JsonValueType type, string ori, int depth)
		{
			this._Value = value;
			this._Type = type;
			this._Depth = depth;
			this.OriginString = ori;
		}

		public readonly string OriginString;

		private object _Value;
		internal object Value
		{
			get
			{
				return this._Value;
			}
		}
		public override string ToString ()
		{
			return string.Format ("[JsonValue: Value={0}, Type={1}]", Value, _Type);
		}

		#region IJsonValue implementation

		private readonly JsonValueType _Type;
		JsonValueType IJsonValue.Type
		{
			get
			{
				return _Type;
			}
		}

		private readonly int _Depth;
		int IJsonValue.Depth
		{
			get
			{
				return _Depth;
			}
		}
		object IJsonValue.ValueOf ()
		{
			if (this.OriginString == null) {
				return this._Value;
			}
			if (_Value is IJsonValue) {
				return (_Value as IJsonValue).ValueOf ();
			} else {
				switch (this._Type) {
				case JsonValueType.Boolean:
					return this.OriginString == "true";
				case JsonValueType.Float:
					double db = double.Parse (this.OriginString);
					return db;
				case JsonValueType.Int:
					long tick = long.Parse (this.OriginString);
					if (tick >= int.MinValue && tick <= int.MinValue) {
						return (int)tick;
					} else {
						return tick;
					}
				case JsonValueType.Null:
					return null;
				case JsonValueType.String:
					return this.OriginString;
				}
				return this.OriginString;
			}
		}

		void IJsonValue.Each(JsonEachMethod m)
		{
			switch (_Type) {
			case JsonValueType.Array:
			case JsonValueType.Object:
				m (null, null, _Type, _Depth);
				(_Value as IJsonValue).Each (m);
				break;
			default:
				m (null, _Value, _Type, _Depth);
				break;
			}
		}

		#endregion


	}
}

